<template>
  <view class="activities-container">
    <view class="waterfall">
      <view class="waterfall-column">
        <view class="activity-item" 
              v-for="(item, index) in leftList" 
              :key="index">
          <image class="activity-image" 
                 :src="item.imageUrl" 
                 mode="widthFix" />
          <view class="activity-info">
            <text class="activity-title">{{ item.title }}</text>
            <view class="activity-period">
              <text class="period-label">报名周期：</text>
              <text class="period-time">{{ item.startTime }} - {{ item.endTime }}</text>
            </view>
            <view class="activity-price">
              <text class="price">¥{{ item.price }}</text>
              <text class="original-price">¥{{ item.originalPrice }}</text>
            </view>
            <button class="signup-btn"
                    :class="{ 'expired': isExpired(item) }"
                    :disabled="isExpired(item)"
                    @click.stop="signUp(item)">
              {{ isExpired(item) ? '期次' : '立即报名' }}
            </button>
          </view>
        </view>
      </view>

      <view class="waterfall-column">
        <view class="activity-item"
              v-for="(item, index) in rightList"
              :key="index"
              @click="goToDetail(item)">
          <image class="activity-image"
                 :src="item.imageUrl"
                 mode="widthFix" />
          <view class="activity-info">
            <text class="activity-title">{{ item.title }}</text>
            <view class="activity-period">
              <text class="period-label">报名周期：</text>
              <text class="period-time">{{ item.startTime }} - {{ item.endTime }}</text>
            </view>
            <view class="activity-price">
              <text class="price">¥{{ item.price }}</text>
              <text class="original-price">¥{{ item.originalPrice }}</text>
            </view>
            <button class="signup-btn"
                    :class="{ 'expired': isExpired(item) }"
                    :disabled="isExpired(item)"
                    @click.stop="signUp(item)">
              {{ isExpired(item) ? '期待下次' : '立即报名' }}
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <view class="loading-more" v-if="loading">加载中...</view>
    <view class="empty-tip" v-if="leftList.length === 0 && rightList.length === 0">
      <image src="/static/images/index_page.png" mode="aspectFit" class="empty-icon"/>
      <text>暂无活动</text>
    </view>
  </view>
</template>

<script>
import config from '@/config/config.js'

export default {
  data() {
    return {
      leftList: [],
      rightList: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      loading: false
    }
  },
  methods: {
    // 跳转到活动详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/subpages/activityDetail/activityDetail?id=${item.id}`
      })
    },
    // 判断活动是否已过期
    isExpired(item) {
      const now = new Date()
      const endDate = new Date(item.endTime)
      return now > endDate
    },
    // 报名活动
    signUp(item) {
      if (this.isExpired(item)) {
        return // 如果已过期，直接返回
      }

      // 检查是否在报名时间内
      const now = new Date()
      const startDate = new Date(item.startTime)

      if (now < startDate) {
        uni.showToast({
          title: '活动未开始',
          icon: 'none'
        })
        return
      }

      uni.showModal({
        title: '确认报名',
        content: `是否报名"${item.title}"活动？`,
        success: (res) => {
          if (res.confirm) {
            // TODO: 处理报名逻辑
            uni.showToast({
              title: '报名成功',
              icon: 'success'
            })
          }
        }
      })
    },
    // 获取活动列表
    async getActivityList(refresh = false) {
      if (this.loading) return
      this.loading = true
      
      try {
        if (refresh) {
          this.pageNum = 1
          this.hasMore = true
          this.leftList = []
          this.rightList = []
        }

        const result = await this.$http.post(config.api.slconfig.slActivityList, {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })
        
        console.log('活动列表响应:', result)
        
        if (result.data.code === 200 || result.data.code === 201) {
          const data = result.data
          const activities = data.rows || []
          
          // 如果返回了最新活动ID，保存到本地
          if (data.lastId) {
            uni.setStorageSync('savedActivityId', data.lastId)
            console.log('更新活动ID:', data.lastId)
          }
          
          // 判断是否还有更多数据
          if (activities.length < this.pageSize) {
            this.hasMore = false
          }
          
          // 处理新数据并添加到现有列表
          activities.forEach((item) => {
            const activity = {
              id: item.id,
              title: item.activityName,
              imageUrl: item.activityImg || '../../static/images/index_page.png',
              startTime: item.activityStartTime,
              endTime: item.activityEndTime,
              price: item.activityMoney,
              originalPrice: item.activityOldMoney
            }
            
            if (this.leftList.length <= this.rightList.length) {
              this.leftList.push(activity)
            } else {
              this.rightList.push(activity)
            }
          })
        }
      } catch (err) {
        console.error('获取活动列表失败:', err)
        uni.showToast({
          title: err.message || '获取活动列表失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    }
  },
  
  async onLoad() {
    try {
      uni.showLoading({
        title: '加载中...'
      })
      // 直接获取活动列表，接口会返回最新ID
      await this.getActivityList(true)
    } catch (err) {
      console.error('页面加载失败:', err)
      uni.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      uni.hideLoading()
    }
  },
  
  // 下拉刷新
  async onPullDownRefresh() {
    try {
      await this.getActivityList(true)
    } catch (err) {
      console.error('刷新失败:', err)
    } finally {
      uni.stopPullDownRefresh()
    }
  },
  
  // 上拉加载更多
  async onReachBottom() {
    if (!this.hasMore || this.loading) return
    
    this.pageNum++
    await this.getActivityList()
  }
}
</script>

<style scoped>
.activities-container {
  padding: 10px;
  background-color: #f5f5f5;
}

.waterfall {
  display: flex;
  justify-content: space-between;
}

.waterfall-column {
  width: 48%;
}

.activity-item {
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.activity-image {
  width: 100%;
  height: auto;
}

.activity-info {
  padding: 10px;
}

.activity-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.activity-period {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.period-label {
  color: #999;
}

.activity-price {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.price {
  font-size: 18px;
  color: #ff4444;
  font-weight: bold;
  margin-right: 8px;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.signup-btn {
  width: 100%;
  height: 32px;
  line-height: 32px;
  background-color: #000000;
  color: #ffffff;
  font-size: 14px;
  border-radius: 16px;
  margin: 0;
  padding: 0;
}

.signup-btn.expired {
  background-color: #cccccc;
  color: #666666;
  cursor: not-allowed;
}

.signup-btn:active:not(.expired) {
  opacity: 0.8;
}

.activity-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #ffffff;
}

.status-ongoing {
  background-color: #00aa00;
}

.status-upcoming {
  background-color: #ff9900;
}

.status-expired {
  background-color: #999999;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100rpx;
  color: #999;
}

.empty-icon {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}
</style>
